package com.xiewz.util;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class WeiBoUtil {
    public static String cookie = "";

    public static String sendPostBase64(String url, String base64) {
        if(cookie == null || cookie.trim().equals("")){
            throw new RuntimeException("请先输入微博登录的Cookie信息！！");
        }
        System.out.println("发送的cookie："+cookie);
        String result = "";
        DataOutputStream out = null;
        BufferedReader in = null;
        try {
            URL url1 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);

            String BOUNDARY = "----WebKitFormBoundaryipOLRDddLCLsZPUN";
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");
            conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("Origin", "chrome-extension://fdfdnfpdplfbbnemmmoklbfjbhecpnhf");
            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
            conn.setRequestProperty("Sec-Fetch-Dest", "empty");
            conn.setRequestProperty("Sec-Fetch-Mode", "zcors");
            conn.setRequestProperty("Sec-Fetch-Site", "none");
            conn.setRequestProperty("Host", "picupload.weibo.com");


            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();

            // 添加参数
            StringBuilder sb1 = new StringBuilder();
            sb1.append("--");
            sb1.append(BOUNDARY);
            sb1.append("\r\n");
            sb1.append("Content-Disposition: form-data; name=\"b64_data\"");
            sb1.append("\r\n");
            sb1.append("\r\n");
            sb1.append(base64);

            // 开始发送请求
            conn.setRequestProperty("Content-Length", sb1.length() + end_data.length + "");
            conn.connect();
            out = new DataOutputStream(conn.getOutputStream());
            out.write(sb1.toString().getBytes());
            out.write(end_data);
            out.flush();


            // 解析响应内容
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }


    /**
     * <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     * <script type="text/javascript">document.domain="sina.com.cn";</script>
     * {
     * "code": "A00006", "data": {
     * "count": 1, "data": "eyJ1aWQiOjM4OTY4NDAxNjQsImFwcCI6Im1pbmlibG9nIiwiY291bnQiOjEsInRpbWUiOjE2MDc4MzM4MDUuMjU5LCJwaWNzIjp7InBpY18xIjp7IndpZHRoIjoxNzk2LCJzaXplIjo0NTc5MTcsInJldCI6MSwiaGVpZ2h0Ijo5MjYsIm5hbWUiOiJwaWNfMSIsInBpZCI6ImU4NDUwZmU0Z3kxZ2xtNGExNDVndmoyMWR3MHBxNDR5In19fQ==", "pics": {"pic_1": {"width": 1796, "size": 457917, "ret": 1, "height": 926, "name": "pic_1", "pid": "e8450fe4gy1glm4a145gvj21dw0pq44y"}}}}
     */
    public static String parseMarkdownImg(String result, String fileName) {
        System.out.println("响应报文: " + result);
        if (result == null || result.trim().equals("")) {
            return null;
        }
        String jsonStr = result.substring(result.indexOf("{"));

        JSONObject parse = (JSONObject) JSONObject.parse(jsonStr);

        if (!"A00006".equals(parse.get("code").toString())) {
            System.out.println("响应结果失败: " + parse.get("code"));
            return null;
        }
        JSONObject data = (JSONObject) parse.get("data");
        JSONObject pics = (JSONObject) data.get("pics");
        JSONObject pic_1 = (JSONObject) pics.get("pic_1");
        String pid = pic_1.get("pid").toString();

        // ![三原色.png](http://ww1.sinaimg.cn/large/e8450fe4gy1gllpmrpedfj21hc13d0ta.jpg)
        String markdownStr = "![" + fileName + "](http://ww1.sinaimg.cn/large/" + pid + ".jpg)";

        return markdownStr;

    }

}
